<template>
  <view class="evaluate-container">
    <!-- 专家信息 -->
    <view class="expert-section">
      <view class="expert-info">
        <u-avatar :src="expert.avatar" size="60"></u-avatar>
        <view class="expert-details">
          <text class="expert-name">{{ expert.name }}</text>
          <text class="expert-title">{{ expert.title }} · {{ expert.hospital }}</text>
        </view>
      </view>
      
      <view class="service-info">
        <text class="service-label">本次服务：</text>
        <text class="service-value">{{ serviceTypeText }}</text>
      </view>
    </view>
    
    <!-- 评分区域 -->
    <view class="rating-section">
      <view class="section-title">服务评价</view>
      
      <view class="rating-items">
        <view 
          v-for="(item, index) in ratingItems" 
          :key="index"
          class="rating-item"
        >
          <text class="rating-label">{{ item.label }}</text>
          <view class="rating-stars">
            <u-icon 
              v-for="star in 5" 
              :key="star"
              name="star-fill" 
              size="28" 
              :color="star <= item.rating ? '#ffd700' : '#e0e0e0'"
              @click="setRating(index, star)"
            ></u-icon>
          </view>
          <text class="rating-text">{{ getRatingText(item.rating) }}</text>
        </view>
      </view>
      
      <view class="overall-rating">
        <text class="overall-label">综合评分</text>
        <view class="overall-stars">
          <u-icon 
            v-for="star in 5" 
            :key="star"
            name="star-fill" 
            size="32" 
            :color="star <= overallRating ? '#ffd700' : '#e0e0e0'"
            @click="setOverallRating(star)"
          ></u-icon>
        </view>
        <text class="overall-score">{{ overallRating }}.0分</text>
      </view>
    </view>
    
    <!-- 标签评价 -->
    <view class="tags-section">
      <view class="section-title">服务标签</view>
      <text class="section-desc">选择最符合本次服务的标签（可多选）</text>
      
      <view class="tags-grid">
        <view 
          v-for="(tag, index) in serviceTags" 
          :key="index"
          class="tag-item"
          :class="{ active: selectedTags.includes(tag) }"
          @click="toggleTag(tag)"
        >
          <text class="tag-text">{{ tag }}</text>
        </view>
      </view>
    </view>
    
    <!-- 文字评价 -->
    <view class="comment-section">
      <view class="section-title">文字评价</view>
      <text class="section-desc">分享您的咨询体验，帮助其他用户</text>
      
      <textarea 
        v-model="commentText"
        class="comment-input"
        placeholder="请详细描述您的咨询体验，如专家的专业程度、服务态度、解答效果等..."
        :maxlength="500"
        auto-height
      ></textarea>
      
      <view class="comment-counter">
        <text class="counter-text">{{ commentText.length }}/500</text>
      </view>
    </view>
    
    <!-- 图片上传 -->
    <view class="images-section">
      <view class="section-title">上传图片</view>
      <text class="section-desc">可上传相关图片作为评价补充（最多3张）</text>
      
      <view class="images-grid">
        <view 
          v-for="(image, index) in uploadedImages" 
          :key="index"
          class="image-item"
        >
          <image :src="image" class="uploaded-image" mode="aspectFill"></image>
          <view class="image-delete" @click="removeImage(index)">
            <u-icon name="close" size="16" color="white"></u-icon>
          </view>
        </view>
        
        <view 
          v-if="uploadedImages.length < 3"
          class="image-upload"
          @click="selectImages"
        >
          <u-icon name="plus" size="24" color="#999"></u-icon>
          <text class="upload-text">添加图片</text>
        </view>
      </view>
    </view>
    
    <!-- 匿名选项 -->
    <view class="anonymous-section">
      <view class="anonymous-option" @click="toggleAnonymous">
        <u-icon 
          :name="isAnonymous ? 'checkbox-mark' : 'checkbox'" 
          size="20" 
          :color="isAnonymous ? '#007aff' : '#ddd'"
        ></u-icon>
        <text class="anonymous-text">匿名评价</text>
      </view>
      <text class="anonymous-desc">选择匿名后，您的用户名和头像将不会显示</text>
    </view>
    
    <!-- 提交按钮 -->
    <view class="submit-section">
      <u-button 
        type="primary"
        class="submit-btn"
        :disabled="!canSubmit || submitting"
        :loading="submitting"
        @click="submitEvaluation"
      >
        {{ submitting ? '提交中...' : '提交评价' }}
      </u-button>
      
      <u-button 
        class="skip-btn"
        @click="skipEvaluation"
      >
        跳过评价
      </u-button>
    </view>
  </view>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { get, post } from '@/utils/request';

// 专家接口
interface Expert {
  id: string;
  name: string;
  avatar: string;
  title: string;
  hospital: string;
}

// 评分项接口
interface RatingItem {
  label: string;
  rating: number;
}

// 评价数据接口
interface EvaluationData {
  orderId: string;
  expertId: string;
  overallRating: number;
  ratingItems: RatingItem[];
  selectedTags: string[];
  commentText: string;
  images: string[];
  isAnonymous: boolean;
}

@Component
export default class EvaluatePage extends Vue {
  // 数据属性
  orderId: string = '';
  expertId: string = '';
  serviceType: string = '';
  
  expert: Expert = {} as Expert;
  
  // 评分相关
  overallRating: number = 5;
  ratingItems: RatingItem[] = [
    { label: '专业程度', rating: 5 },
    { label: '服务态度', rating: 5 },
    { label: '解答效果', rating: 5 },
    { label: '响应速度', rating: 5 }
  ];
  
  // 标签相关
  selectedTags: string[] = [];
  serviceTags: string[] = [
    '专业权威', '耐心细致', '回复及时', '解答清晰',
    '态度友好', '经验丰富', '建议实用', '服务周到',
    '值得推荐', '物超所值'
  ];
  
  // 评价内容
  commentText: string = '';
  uploadedImages: string[] = [];
  isAnonymous: boolean = false;
  
  submitting: boolean = false;
  
  // 计算属性
  get serviceTypeText(): string {
    const typeMap: Record<string, string> = {
      text: '图文咨询',
      voice: '语音咨询',
      video: '视频咨询'
    };
    return typeMap[this.serviceType] || '咨询服务';
  }
  
  get canSubmit(): boolean {
    return this.overallRating > 0;
  }
  
  // 生命周期
  onLoad(options: any) {
    this.orderId = options.orderId || '';
    this.expertId = options.expertId || '';
    this.serviceType = options.serviceType || 'text';
    
    if (this.expertId) {
      this.loadExpertInfo();
    }
  }
  
  // 方法
  
  /**
   * 加载专家信息
   */
  async loadExpertInfo() {
    try {
      const response = await get(`/experts/detail/${this.expertId}`);
      this.expert = response.data.expert;
    } catch (error) {
      console.error('加载专家信息失败:', error);
      
      // 使用模拟数据
      this.expert = this.getMockExpert();
    }
  }
  
  /**
   * 设置单项评分
   */
  setRating(itemIndex: number, rating: number) {
    this.ratingItems[itemIndex].rating = rating;
    this.updateOverallRating();
  }
  
  /**
   * 设置综合评分
   */
  setOverallRating(rating: number) {
    this.overallRating = rating;
    
    // 同步更新各项评分
    this.ratingItems.forEach(item => {
      item.rating = rating;
    });
  }
  
  /**
   * 更新综合评分
   */
  updateOverallRating() {
    const total = this.ratingItems.reduce((sum, item) => sum + item.rating, 0);
    this.overallRating = Math.round(total / this.ratingItems.length);
  }
  
  /**
   * 获取评分文字
   */
  getRatingText(rating: number): string {
    const ratingTexts = ['', '很差', '较差', '一般', '满意', '非常满意'];
    return ratingTexts[rating] || '';
  }
  
  /**
   * 切换标签选择
   */
  toggleTag(tag: string) {
    const index = this.selectedTags.indexOf(tag);
    if (index > -1) {
      this.selectedTags.splice(index, 1);
    } else {
      this.selectedTags.push(tag);
    }
  }
  
  /**
   * 选择图片
   */
  selectImages() {
    const remainingCount = 3 - this.uploadedImages.length;
    
    uni.chooseImage({
      count: remainingCount,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const filePaths = Array.isArray(res.tempFilePaths) ? res.tempFilePaths : [res.tempFilePaths];
        this.uploadImages(filePaths);
      }
    });
  }
  
  /**
   * 上传图片
   */
  async uploadImages(imagePaths: string[]) {
    uni.showLoading({
      title: '上传中...'
    });
    
    try {
      for (const imagePath of imagePaths) {
        const uploadResponse = await this.uploadImage(imagePath);
        this.uploadedImages.push(uploadResponse.url);
      }
    } catch (error) {
      console.error('上传图片失败:', error);
      uni.showToast({
        title: '上传失败',
        icon: 'none'
      });
    } finally {
      uni.hideLoading();
    }
  }
  
  /**
   * 上传单张图片
   */
  async uploadImage(imagePath: string): Promise<{ url: string }> {
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: '/api/upload/image',
        filePath: imagePath,
        name: 'file',
        success: (res) => {
          try {
            const data = JSON.parse(res.data);
            resolve(data);
          } catch (error) {
            reject(error);
          }
        },
        fail: reject
      });
    });
  }
  
  /**
   * 删除图片
   */
  removeImage(index: number) {
    this.uploadedImages.splice(index, 1);
  }
  
  /**
   * 切换匿名状态
   */
  toggleAnonymous() {
    this.isAnonymous = !this.isAnonymous;
  }
  
  /**
   * 提交评价
   */
  async submitEvaluation() {
    if (!this.canSubmit) {
      uni.showToast({
        title: '请完成评价',
        icon: 'none'
      });
      return;
    }
    
    this.submitting = true;
    
    try {
      const evaluationData: EvaluationData = {
        orderId: this.orderId,
        expertId: this.expertId,
        overallRating: this.overallRating,
        ratingItems: this.ratingItems,
        selectedTags: this.selectedTags,
        commentText: this.commentText.trim(),
        images: this.uploadedImages,
        isAnonymous: this.isAnonymous
      };
      
      await post('/evaluations/submit', evaluationData);
      
      uni.showToast({
        title: '评价成功',
        icon: 'success'
      });
      
      // 延迟跳转
      setTimeout(() => {
        this.navigateBack();
      }, 1500);
      
    } catch (error) {
      console.error('提交评价失败:', error);
      uni.showToast({
        title: '提交失败，请重试',
        icon: 'none'
      });
    } finally {
      this.submitting = false;
    }
  }
  
  /**
   * 跳过评价
   */
  skipEvaluation() {
    uni.showModal({
      title: '跳过评价',
      content: '确定要跳过本次评价吗？您可以稍后在订单详情中进行评价。',
      success: (res) => {
        if (res.confirm) {
          this.navigateBack();
        }
      }
    });
  }
  
  /**
   * 返回上一页
   */
  navigateBack() {
    // 根据来源页面决定跳转目标
    const pages = getCurrentPages();
    if (pages.length > 1) {
      uni.navigateBack();
    } else {
      uni.switchTab({
        url: '/pages/index/index'
      });
    }
  }
  
  /**
   * 获取模拟专家数据
   */
  getMockExpert(): Expert {
    return {
      id: this.expertId,
      name: '张医生',
      avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=professional%20pediatrician%20doctor&image_size=square',
      title: '主任医师',
      hospital: '北京儿童医院'
    };
  }
}
</script>

<style lang="scss" scoped>
.evaluate-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 40rpx;
}

.expert-section {
  background-color: white;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .expert-info {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    
    .expert-details {
      flex: 1;
      margin-left: 20rpx;
      
      .expert-name {
        display: block;
        font-size: 30rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .expert-title {
        font-size: 26rpx;
        color: #666;
      }
    }
  }
  
  .service-info {
    display: flex;
    align-items: center;
    
    .service-label {
      font-size: 26rpx;
      color: #666;
      margin-right: 10rpx;
    }
    
    .service-value {
      font-size: 26rpx;
      color: #007aff;
      font-weight: 600;
    }
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 10rpx;
}

.section-desc {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 20rpx;
}

.rating-section {
  background-color: white;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .rating-items {
    margin-bottom: 30rpx;
    
    .rating-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .rating-label {
        font-size: 28rpx;
        color: #333;
        width: 120rpx;
      }
      
      .rating-stars {
        display: flex;
        gap: 8rpx;
        flex: 1;
        justify-content: center;
      }
      
      .rating-text {
        font-size: 24rpx;
        color: #666;
        width: 100rpx;
        text-align: right;
      }
    }
  }
  
  .overall-rating {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 30rpx 0;
    border-top: 1rpx solid #f0f0f0;
    
    .overall-label {
      font-size: 30rpx;
      font-weight: 600;
      color: #333;
      margin-right: 20rpx;
    }
    
    .overall-stars {
      display: flex;
      gap: 10rpx;
      margin-right: 20rpx;
    }
    
    .overall-score {
      font-size: 28rpx;
      font-weight: 600;
      color: #ff4757;
    }
  }
}

.tags-section {
  background-color: white;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .tags-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 15rpx;
    
    .tag-item {
      padding: 15rpx 25rpx;
      background-color: #f8f8f8;
      border: 1rpx solid #e0e0e0;
      border-radius: 25rpx;
      transition: all 0.3s;
      
      &.active {
        background-color: #e6f3ff;
        border-color: #007aff;
        
        .tag-text {
          color: #007aff;
        }
      }
      
      .tag-text {
        font-size: 26rpx;
        color: #666;
      }
    }
  }
}

.comment-section {
  background-color: white;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .comment-input {
    width: 100%;
    min-height: 200rpx;
    padding: 20rpx;
    background-color: #f8f8f8;
    border-radius: 12rpx;
    font-size: 28rpx;
    color: #333;
    line-height: 1.5;
    border: none;
    resize: none;
  }
  
  .comment-counter {
    text-align: right;
    margin-top: 10rpx;
    
    .counter-text {
      font-size: 22rpx;
      color: #999;
    }
  }
}

.images-section {
  background-color: white;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .images-grid {
    display: flex;
    gap: 15rpx;
    
    .image-item {
      position: relative;
      width: 150rpx;
      height: 150rpx;
      
      .uploaded-image {
        width: 100%;
        height: 100%;
        border-radius: 12rpx;
      }
      
      .image-delete {
        position: absolute;
        top: -8rpx;
        right: -8rpx;
        width: 32rpx;
        height: 32rpx;
        background-color: #ff4757;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    
    .image-upload {
      width: 150rpx;
      height: 150rpx;
      background-color: #f8f8f8;
      border: 2rpx dashed #ddd;
      border-radius: 12rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      
      .upload-text {
        font-size: 22rpx;
        color: #999;
        margin-top: 8rpx;
      }
    }
  }
}

.anonymous-section {
  background-color: white;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .anonymous-option {
    display: flex;
    align-items: center;
    margin-bottom: 10rpx;
    
    .anonymous-text {
      margin-left: 10rpx;
      font-size: 28rpx;
      color: #333;
    }
  }
  
  .anonymous-desc {
    font-size: 24rpx;
    color: #999;
    margin-left: 30rpx;
  }
}

.submit-section {
  padding: 0 30rpx;
  
  .submit-btn {
    width: 100%;
    height: 80rpx;
    font-size: 32rpx;
    font-weight: 600;
    margin-bottom: 20rpx;
  }
  
  .skip-btn {
    width: 100%;
    height: 80rpx;
    font-size: 28rpx;
    background-color: #f8f8f8;
    color: #666;
    border: none;
  }
}
</style>